/**  
* @Title: BbdHelper.java
* @Package org.zsen.crawler
* @Description TODO
* @author ZhangSen
* @date 2015年11月1日 下午8:14:53
* @version 
*/ 
package org.zsen.crawler;

import java.io.File;

import com.sleepycat.je.Cursor;
import com.sleepycat.je.Database;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;

import cn.edu.hfut.dmic.webcollector.util.BerkeleyDBUtils;

/**
* @ClassName: BbdHelper
* @Description: 
* @author ZhangSen
* @date 2015年11月1日 下午8:14:53
*
*/
public abstract class BbdHelper {
	
	private File dir;
	private Environment env;
	private EnvironmentConfig config=new EnvironmentConfig();
	private String database_name;
	private boolean read=false,write=false;
	
	public boolean isRead() {
		return read;
	}

	public void setRead(boolean read) {
		this.read = read;
	}

	public boolean isWrite() {
		return write;
	}

	public void setWrite(boolean write) {
		this.write = write;
	}

	public String getDatabase_name() {
		return database_name;
	}

	public void setDatabase_name(String database_name) {
		this.database_name = database_name;
	}

	public BbdHelper(String path)
	{
		dir=new File(path);
		if(!dir.exists())
			dir.mkdirs();
		config.setAllowCreate(true);
		env=new Environment(dir, config);
	}
	
	public Database getDataBase(String name)
	{
		return env.openDatabase(null, name, BerkeleyDBUtils.defaultDBConfig);
	}
	
	public void execute(String name)
	{
		Database db=getDataBase(name);
		Cursor cursor=null;
		if(read)
		{
			cursor=db.openCursor(null, null);
			read(cursor);
		}
		if(write)
			write(db);
		
		if(cursor!=null)
			cursor.close();
		if(db!=null)
		{
			db.sync();
			db.close();
		}
		
	}
	public void execute()
	{
		if(null==database_name)
			throw new IllegalArgumentException("database_name is null");
		execute(database_name);
	}
	
	
	abstract void read(Cursor cursor);
	abstract void write(Database db);
}
